//
//  chatListVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/7/20.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "chatListVC.h"
#import "RCDCheckVersion.h"
#import "RongYunListCell.h"
#import "addNewFriend.h"
#import "searchContactsVC.h"
#import "friendListVC.h"
#import "LSManyPeopleChatVC.h"
#import "systemInfo.h"

@interface chatListVC ()
@property (strong, nonatomic)NSArray * titleArr;
- (void)updateBadgeValueForTabBarItem;
@end

@implementation chatListVC

-(NSArray *)titleArr{

    if (!_titleArr) {
        _titleArr = [NSArray array];
    }
    return _titleArr;

}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];
    
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        
        NSArray *list=self.navigationController.navigationBar.subviews;
        
        for (id obj in list) {
            
            if ([obj isKindOfClass:[UIImageView class]]) {
                
                UIImageView *imageView=(UIImageView *)obj;
                
                NSArray *list2=imageView.subviews;
                
                for (id obj2 in list2) {
                    
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        
                        UIImageView *imageView2=(UIImageView *)obj2;
                        
                        imageView2.hidden=YES;
                        
                    }
                    
                }
                
            }
            
        }
        
    }
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:19],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    [self setDisplayConversationTypes:@[@(ConversationType_PRIVATE),@(ConversationType_SYSTEM),@(ConversationType_DISCUSSION)]];
    
    [self updateBadgeValueForTabBarItem];
    
    self.tabBarController.tabBar.hidden = NO;
    
    [[RCIMClient sharedRCIMClient] setConversationToTop:ConversationType_SYSTEM targetId:@"lswxttz" isTop:YES];
    
   
}

- (void)updateBadgeValueForTabBarItem {
    __weak typeof(self) __weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
//        int count = [[RCIMClient sharedRCIMClient]
//                     getUnreadCount:self.displayConversationTypeArray];
        
        int count = [[RCIMClient sharedRCIMClient]
                     getTotalUnreadCount];
        
        if (count > 0) {
            //      __weakSelf.tabBarItem.badgeValue =
            //          [[NSString alloc] initWithFormat:@"%d", count];
            
//            int sysCount = [[RCIMClient sharedRCIMClient]getUnreadCount:@[@(ConversationType_SYSTEM)]];

//            NSArray * arr = [[RCIMClient sharedRCIMClient]getHistoryMessages:ConversationType_SYSTEM targetId:[USER_DEFAULTS objectForKey:@"account"] oldestMessageId:-1 count:count];

            
            [__weakSelf.tabBarController.tabBar showBadgeOnItemIndex:1];
            
            
        }else{
            
            [__weakSelf.tabBarController.tabBar hideBadgeOnItemIndex:1];
        
        }
    });
}

- (void)notifyUpdateUnreadMessageCount {
    
    [self updateBadgeValueForTabBarItem];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    self.title = @"最近联系人";
    
    [self setDisplayConversationTypes:@[@(ConversationType_PRIVATE),@(ConversationType_SYSTEM),@(ConversationType_DISCUSSION)]];
    
    [[RCIMClient sharedRCIMClient] setConversationToTop:ConversationType_SYSTEM targetId:@"lswxttz" isTop:YES];

    
    [self updateBadgeValueForTabBarItem];
    
    // 声明这张图片用原图(别渲染)
    UIImage *selectedImgitemHome = [UIImage imageNamed:@"xx"];
    selectedImgitemHome = [selectedImgitemHome imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.navigationController.tabBarItem setSelectedImage:selectedImgitemHome];
    
    //右item
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTarget:self action:@selector(rightBtn) image:@"加好友" highImage:@"加好友"];
    self.navigationItem.rightBarButtonItem = rightItem;
    

    self.conversationListTableView.separatorColor =
    [UIColor colorWithHexString:@"dfdfdf" alpha:1.0f];
    self.conversationListTableView.tableFooterView = [UIView new];

}

-(void)rightBtn{

    searchContactsVC * addFriend = [[searchContactsVC alloc]init];
    [self.navigationController pushViewController:addFriend animated:YES];

}

//插入自定义会话model
- (NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource{

        _titleArr = @[@"我的好友",@"发起群聊"];

    for (int i = 0; i<_titleArr.count; i++) {
        RCConversationModel *model = [[RCConversationModel alloc]init];
        model.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        model.conversationTitle = _titleArr[i];
        model.isTop = YES;
        [dataSource insertObject:model atIndex:i];
    }
    return dataSource;
}

#pragma mark - 设置cell的删除事件
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    RCConversationModel *model = [self.conversationListDataSource objectAtIndex:indexPath.row];
    if(model.conversationModelType == RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION){
        return UITableViewCellEditingStyleNone;
    }else{
        return UITableViewCellEditingStyleDelete;
    }
}

#pragma mark - 修改cell样式
- (void)willDisplayConversationTableCell:(RCConversationBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath{
    
    RCConversationModel *model = [self.conversationListDataSource objectAtIndex:indexPath.row];
    
    
    if(model.conversationModelType != RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION && model.conversationType == ConversationType_SYSTEM){
        
        RCConversationCell *RCcell = (RCConversationCell *)cell;
        RCcell.conversationTitle.font = [UIFont fontWithName:@"PingFangSC-Light" size:14];
        RCcell.messageContentLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:12];
        RCcell.messageCreatedTimeLabel.font = [UIFont fontWithName:@"PingFangSC-Light" size:12];
       
        
    }    

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

-(RCConversationBaseCell *)rcConversationListTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RongYunListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RongYunListCell"];
    
    if (!cell) {
        cell = [[RongYunListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RongYunListCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
//    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    
    cell.headImg.image = [UIImage imageNamed:@"我的--好友"];
    cell.titleLabel.text = _titleArr[indexPath.row];
    
    return cell;
}

- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath{
    
    [self.conversationListTableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(model.conversationModelType == RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION){
        
        NSString *cellTitle = model.conversationTitle;
        friendListVC * friendList = [[friendListVC alloc]init];
        LSManyPeopleChatVC * LSManyPeopleChat = [[LSManyPeopleChatVC alloc]init];
        switch (indexPath.row) {
            case 0:
                
                //好友列表
                
                [self.navigationController pushViewController:friendList animated:YES];
                break;
                
            case 1:
                [self.navigationController pushViewController:LSManyPeopleChat animated:YES];
                break;
            default:
                break;
        }
        
    }else if (model.conversationType == ConversationType_PRIVATE){
        
        IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
        manager.enable = NO;
        manager.shouldResignOnTouchOutside = NO;
        manager.shouldToolbarUsesTextFieldTintColor = NO;
        manager.enableAutoToolbar = NO;
        
        sessionVC *chatVc = [[sessionVC alloc] init];
        chatVc.title = model.conversationTitle;
        chatVc.conversationType = ConversationType_PRIVATE;
        chatVc.targetId = model.targetId;
        chatVc.enableUnreadMessageIcon = YES;
        chatVc.enableNewComingMessageIcon = YES;
        chatVc.defaultHistoryMessageCountOfChatRoom = 50;
        model.hasUnreadMentioned = YES;
        
        
        self.tabBarController.tabBar.hidden = YES;
        
        [self.navigationController pushViewController:chatVc animated:YES];
        

        
    }else if (model.conversationType == ConversationType_SYSTEM){
        NSLog(@"%@",model.lastestMessage);

        [[RCIMClient sharedRCIMClient] setConversationToTop:ConversationType_SYSTEM targetId:model.targetId isTop:YES];
        
        systemInfo *systemInfoVC = [[systemInfo alloc] init];
        
        RCTextMessage *textMessage = (RCTextMessage *)model.lastestMessage;
        NSString *jsonStr = textMessage.extra;
        //判断jsonStr里是否包含@"type:1"
        if ([jsonStr rangeOfString:@"type:1"].location != NSNotFound) {
            NSLog(@"1");
            systemInfoVC.msgStrTig = @"好友邀请";
        }else{
            systemInfoVC.msgStrTig = @"消息通知";
        }
        [self.navigationController pushViewController:systemInfoVC animated:YES];
//        addNewFriend * addNewFri = [[addNewFriend alloc]init];
//        [self.navigationController pushViewController:addNewFri animated:YES];
        [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_SYSTEM targetId:model.targetId];
        
    }else if (model.conversationType == ConversationType_DISCUSSION){
    
        IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
        manager.enable = NO;
        manager.shouldResignOnTouchOutside = NO;
        manager.shouldToolbarUsesTextFieldTintColor = NO;
        manager.enableAutoToolbar = NO;
        
        NSArray * arr = [USER_DEFAULTS arrayForKey:@"TaoLunZu"];
        
        sessionVC *chatVc = [[sessionVC alloc] init];
        
        chatVc.conversationType = ConversationType_DISCUSSION;
        chatVc.targetId = model.targetId;
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        dict[@"discussionId"] = model.targetId;
        dict[@"discussionName"] = model.conversationTitle;

        chatVc.tlzDict = dict;
        
        //获取讨论组信息
        [[RCIMClient sharedRCIMClient] getDiscussion:model.targetId success:^(RCDiscussion *discussion) {
            NSLog(@"当前讨论组信息:%@",discussion.creatorId);
            dict[@"creatorId"] = discussion.creatorId;
            dict[@"peopleList"] = @(discussion.memberIdList.count);
        } error:^(RCErrorCode status) {
            NSLog(@"create discussion Failed &gt; %ld!", (long)status);
        }];
        

        chatVc.discussionId = model.targetId;
        chatVc.title = model.conversationTitle;
        chatVc.enableUnreadMessageIcon = YES;
        chatVc.enableNewComingMessageIcon = YES;
        chatVc.defaultHistoryMessageCountOfChatRoom = 50;
        model.hasUnreadMentioned = YES;
        
        chatVc.style = @"讨论组";
        
        self.tabBarController.tabBar.hidden = YES;
        
        [self.navigationController pushViewController:chatVc animated:YES];
    
    }

}

- (void)didReceiveMessageNotification:(NSNotification *)notification{
    
    [[RCIMClient sharedRCIMClient] setConversationToTop:ConversationType_SYSTEM targetId:@"lswxttz" isTop:YES];
    
    
    __weak typeof(self) __weakSelf = self;

    [__weakSelf.tabBarController.tabBar showBadgeOnItemIndex:1];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //调用父类刷新未读消息数
        [super didReceiveMessageNotification:notification];
        
    });
    
    dispatch_async(dispatch_get_main_queue(), ^{

        [self notifyUpdateUnreadMessageCount];
        
        //当消息为RCContactNotificationMessage时，没有调用super，如果是最后一条消息，可能需要刷新一下整个列表。
        //原因请查看super didReceiveMessageNotification的注释。
        NSNumber *left =
        [notification.userInfo objectForKey:@"left"];
        if (0 == left.integerValue) {
            [super refreshConversationTableViewIfNeeded];
        }
    });

}

//左滑删除
- (void)rcConversationListTableView:(UITableView *)tableView
                 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
                  forRowAtIndexPath:(NSIndexPath *)indexPath {
    //可以从数据库删除数据
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_SYSTEM
                                             targetId:model.targetId];
    [self.conversationListDataSource removeObjectAtIndex:indexPath.row];
    [self.conversationListTableView reloadData];
}

//高度
- (CGFloat)rcConversationListTableView:(UITableView *)tableView
               heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 67.0f;
}


@end
